<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.sinosoft.perfect.system._.vo.LoginUser"%>
<%@page import="com.sinosoft.perfect.system._.po.TUnit"%>
<%@ include file="/page/common/commonConfig.jsp" %>
<%
	List<TUnit> list = ((LoginUser)session.getAttribute("user")).getUnits();
	String unitIds = "";
	for(int i=0; i<list.size(); i++){
		if(i==0)
			unitIds += list.get(0).getUnitId();
		else
			unitIds += ("," + list.get(i).getUnitId());
	}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>
    <title>组织机构-用户</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<script src="<%=basePath%>component/layout.js"></script>
    <script src="<%=basePath%>component/tree.js"></script>
    <script src="<%=basePath%>component/tabbar.js"></script>
    <script src="<%=basePath%>component/grid.js"></script>
    <script src="<%=basePath%>component/toolbar.js"></script>
    <script type="text/javascript" src="<%=basePath%>dwrsystem/engine.js"></script>
	<script type="text/javascript" src="<%=basePath%>dwrsystem/interface/UserRolebusinessAuthorize.js"></script>
	<script type="text/javascript" src="<%=basePath%>dwrsystem/engine.js"></script>
	<script type="text/javascript" src="<%=basePath%>dwrsystem/interface/UserRolesystemAuthorize.js"></script>
	<script type="text/javascript" src="<%=basePath%>dwrsystem/interface/userService.js"></script> 
	<script type="text/javascript" src="<%=basePath%>dwrsystem/engine.js"></script>
	<script type="text/javascript">
	var unitWindow;
	var userWindow;
	var childDhxLayout;
	var myBusinessGrid;
	var mySystemGrid;
	var bindDirection;//在绑定时，判断是绑定一个组织下的所有人员还是单个用户
	var addUserWindow;
	
	var dhxLayout = createLayoutNormal('3W',false,true);
	
	$(function (){
		initContainerBaseLayout();
		initTree();
		initInputEventForSystem();
		initInputEventForBusiness();
	});
	
	function initContainerBaseLayout(){
		dhxLayout.cells('a').hideHeader();
		dhxLayout.cells('a').setWidth(Number('260'));
		dhxLayout.cells('b').hideHeader();
		changeRightPage('<%=basePath%>page/system/user/user_list_detach.jsp');
		dhxLayout.cells('c').hideHeader();
		dhxLayout.cells('c').setWidth(Number('265'));
		configCLayout();
	}
	
	function reloadSystemAndBusinessGrid(detachUserId){
		userId = detachUserId;
		reloadGridTypeUser(detachUserId);
	}
	
	function initTree(){
		MyTree.initMyTreeFromLayout(dhxLayout,"a");
		MyTree.setXmlAutoLoad('<%=basePath%>system-user/UserAction!userTreeChild.action');
		MyTree.setupTree("<%=basePath%>system-user/UserAction!userTree.action", nodeOnclick);
	}
	
	var userId;//绑定时会用到
	var myTreeOfUnitId;//绑定时会用到
	function nodeOnclick(id){
		var type = MyTree.getUserDataAttr(id, "type");
		var unitId = MyTree.getUserDataAttr(id, "unitId");
		var src;
		var optLevel = '${power.operationLevel}';
		if('${user.userMainId}' == 1 || optLevel == 0){
			if(type == 'user' ){
				if(id.indexOf('|') != -1){
					id = id.substring(0, id.indexOf('|'));
				}
				//src = '<%=basePath%>page/system/user/main_right_user.jsp?userId=' + id;
				userId = id;
				createTabbarFromDHXLayoutCell(dhxLayout.cells('b'),operateTabbar);
				reloadGridTypeUser(id);
			} else {
				myTreeOfUnitId = id;
				src = '<%=basePath %>page/system/user/user_list.jsp?unitId='+ id;
				MyTree.openNode(id);
				changeRightPage(src);
				reloadGridTypeOrganation(id);
			}
		} else {
			if (optLevel > 0 && optLevel <= 100) {
				if(type == 'user'){
					var treeId = id;
					if(id.indexOf('|') != -1){
						id = id.substring(0, id.indexOf('|'));
					}
					var exitsUnitIds = document.getElementById('sessionUserUnitIds').value;
					var currentUserUnitId = MyTree.getParentNodeId(treeId);
					if(isExitsInfoForGreaterZero(currentUserUnitId)){
						//src = '<%=basePath%>page/system/user/main_right_user.jsp?userId=' + id;
						userId = id;
						createTabbarFromDHXLayoutCell(dhxLayout.cells('b'),operateTabbar);
						reloadGridTypeUser(id);
					}else{
						parent.parent.parent.parent.notifyWarn('您没有足够的权限来本操作单位的用户!');
						return;
					}
				} else {//点击单位
					var level = MyTree.getNodeLevel(id);
					var exitsUnitIds = document.getElementById('sessionUserUnitIds').value;
					if(exitsUnitIds.indexOf(id) == -1){
						var possibleUnitIds = getAllParentPossibleUnitIds(exitsUnitIds);
						if(possibleUnitIds.indexOf(id) == -1){
							//MyTree.openNode(id);
							parent.parent.parent.parent.notifyWarn('您没有足够的权限来操作本单位!');
							return;
						}else{
							myTreeOfUnitId = id;
							src = '<%=basePath %>page/system/user/user_list.jsp?unitId='+ id;
							MyTree.openNode(id);
							changeRightPage(src);
							reloadGridTypeOrganation(id);
						}
					}else{
						myTreeOfUnitId = id;
						src = '<%=basePath %>page/system/user/user_list.jsp?unitId='+ id;
						MyTree.openNode(id);
						changeRightPage(src);
						reloadGridTypeOrganation(id);
					}
				}
			}else if(optLevel <0 && optLevel > -100){
				if(type == 'user' ){
					var treeId = id;
					if(id.indexOf('|') != -1){
						id = id.substring(0, id.indexOf('|'));
					}
					var exitsUnitIds = document.getElementById('sessionUserUnitIds').value;
					var currentUserUnitId = MyTree.getParentNodeId(treeId);
					if(isExitsInfoForLowZero(currentUserUnitId)){
						//src = '<%=basePath%>page/system/user/main_right_user.jsp?userId=' + id;
						userId = id;
						createTabbarFromDHXLayoutCell(dhxLayout.cells('b'),operateTabbar);
						reloadGridTypeUser(id);
					}else{
						parent.parent.parent.parent.notifyWarn('您没有足够的权限来本操作单位的用户!');
						return;
					}
				} else {
					var exitsUnitIds = document.getElementById('sessionUserUnitIds').value;
					if(exitsUnitIds.indexOf(id) == -1){
						var possibleUnitIds = getAllSubPossibleUnitIds(exitsUnitIds);
						if(possibleUnitIds.indexOf(id) == -1){
							parent.parent.parent.parent.notifyWarn('您没有足够的权限来操作本单位!');
							return;
						}else{
							myTreeOfUnitId = id;
							src = '<%=basePath %>page/system/user/user_list.jsp?unitId='+ id;
							MyTree.openNode(id);
							changeRightPage(src);
							reloadGridTypeOrganation(id);
						}
					}else{
						myTreeOfUnitId = id;
						src = '<%=basePath %>page/system/user/user_list.jsp?unitId='+ id;
						MyTree.openNode(id);
						changeRightPage(src);
						reloadGridTypeOrganation(id);
					}
				}
			}
		}
	}
	
	function isExitsInfoForGreaterZero(currentUserUnitId){
		var exitsUnitIds = document.getElementById('sessionUserUnitIds').value;
		if(exitsUnitIds.indexOf(currentUserUnitId) >= 0){
			return true;
		}
		var possibleUnitIds = getAllParentPossibleUnitIds(exitsUnitIds);
		if(possibleUnitIds.indexOf(currentUserUnitId) >= 0){
			return true;
		}
		return false;
	}
	
	function isExitsInfoForLowZero(currentUserUnitId){
		var exitsUnitIds = document.getElementById('sessionUserUnitIds').value;
		if(exitsUnitIds.indexOf(currentUserUnitId) >= 0){
			return true;
		}
		var possibleUnitIds = getAllSubPossibleUnitIds(exitsUnitIds);
		if(possibleUnitIds.indexOf(currentUserUnitId) >= 0){
			return true;
		}
		return false;
	}

	
	function getAllParentPossibleUnitIds(exitsUnitIds){
		var allPossibleUnitIds = '';
		var unitIds = exitsUnitIds.split(',');
		for(var i=0;i<unitIds.length;i++){
			var pId = unitIds[i];
			while(MyTree.getNodeLevel(pId) > 0){
				allPossibleUnitIds += pId+",";
				pId = MyTree.getParentNodeId(pId);
			}
		}
		return allPossibleUnitIds;
	}
	
	function getAllSubPossibleUnitIds(exitsUnitIds){
		var allPossibleUnitIds = '';
		var unitIds = exitsUnitIds.split(",");
		for(var i=0;i<unitIds.length;i++){
			if(i==0){
				allPossibleUnitIds += MyTree.getMyTree().getAllSubItems(unitIds[i]);
			}else{
				allPossibleUnitIds += ("," + MyTree.getMyTree().getAllSubItems(unitIds[i]));
			}
		}
		return allPossibleUnitIds;
	}
	
	function deleteUserOnTree(userId,unId){//getAllSubItems(unId)openAllItems
		var ids = MyTree.getMyTree().getAllChildless().split(',');
		for(var i=0;i<ids.length;i++){
			if(ids[i].indexOf(userId) != -1){
				MyTree.delNode(ids[i]);
			}
		}
	}
	
	function reloadGridTypeOrganation(id){
		bindDirection = 'oragnation';
		myBusinessGrid.clearAndLoad('<%=basePath%>system-roleBusiness/RoleBusinessAction!roleBusinessGridForBindAUnit.action?unitId=');
		mySystemGrid.clearAndLoad('<%=basePath%>system-roleSystem/RoleSystemAction!roleSystemGridForBindAUnit.action?unitId=');
	}
	
	function reloadGridTypeUser(id){
		bindDirection = 'user';
		myBusinessGrid.clearAndLoad('<%=basePath%>system-roleBusiness/RoleBusinessAction!roleBusinessGridForBindAUnitUsers.action?userId=' + id);
		mySystemGrid.clearAndLoad('<%=basePath%>system-roleSystem/RoleSystemAction!roleSystemGridForBindAUnitUsers.action?userId=' + id);
	}
	
	function createNoUnitUsersTabbar(createNoUnitUserId){
		userId = createNoUnitUserId;
		createTabbarFromDHXLayoutCell(dhxLayout.cells('b'),operateTabbar);
	}
	
	function configCLayout(){
		childDhxLayout = dhxLayout.cells("c").attachLayout("2E");
		var a = childDhxLayout.cells('a');
		var b = childDhxLayout.cells('b');
		a.hideHeader();
		b.hideHeader();
		mySystemGrid = createGridFromLayoutCell(childDhxLayout.cells('a'));
		configGridSystem();
		configToobarSystem();
		myBusinessGrid = createGridFromLayoutCell(childDhxLayout.cells('b'));
		configGridBusiness();
		configToobarBusiness();
	}
	
	function configToobarBusiness(){
		if(power.getPower() != '' && power.getPowerUpdate()){
			createToolbarFromDHXLayoutCell(childDhxLayout.cells('b'),function(toolbar){
				var myBusinessToolbar = toolbar;
			    myBusinessToolbar.addText("info", 1, "业务角色:");
			    myBusinessToolbar.addSeparator("sep1", 2);
			    if(power.getPowerUpdate())myBusinessToolbar.addButton("update", 3, "绑定", "link_go.png", "link_go.png");
			    myBusinessToolbar.addInput("queryBusiness", 4, "", "100");
			    myBusinessToolbar.attachEvent("onClick", function(id) {
			    	if(id == 'update'){
			    		dhxBusinessGrid.bind();
			    	}
			    });
			});
		}
	}
	
	
	function configToobarSystem(){
		if(power.getPower() != '' && power.getPowerUpdate())
			createToolbarFromDHXLayoutCell(childDhxLayout.cells('a'),function(toolbar){
				var mySystemToolbar = toolbar;
			    mySystemToolbar.addText("info", 1, "系统角色:");
			    mySystemToolbar.addSeparator("sep1", 2);
			    if(power.getPowerUpdate()) mySystemToolbar.addButton("update", 3, "绑定", "link_go.png", "link_go.png");
			    mySystemToolbar.addInput("querySystem", 4, "", "100");
			    mySystemToolbar.attachEvent("onClick", function(id) {
			    	if(id == 'update'){
			    		dhxSystemGrid.bind();
			    	}
			    });
			});
	}
	
	function configGridBusiness(){
		myBusinessGrid.setHeader('');
		myBusinessGrid.setNoHeader(true);
	    myBusinessGrid.setColAlign("center");
	    myBusinessGrid.setColTypes("ro");
	    myBusinessGrid.enableMultiselect(true);
	    myBusinessGrid.init();
	    setSkin(myBusinessGrid);
	    myBusinessGrid.loadXML('<%=basePath%>system-roleBusiness/RoleBusinessAction!roleBusinessGridForBindAUnitUsers.action?userId=');
	}
	
	var dhxBusinessGrid = {
		bind : function (){
			if(bindDirection == 'oragnation'){
				layoutProgressOn(dhxLayout);
				UserRolebusinessAuthorize.delAllRoleUsersOfUnitAndAddUsersRoleOfUnit(myTreeOfUnitId, myBusinessGrid.getSelectedId(),
	   				function(data){
	   					if(data == true){
	   						parent.notifyCreater('业务角色绑定成功');layoutProgressOff(dhxLayout);
	   					}else{
	   						parent.notifyWarn('业务角色绑定失败');layoutProgressOff(dhxLayout);
	   					}
	   				}
	   			);
			}else if(bindDirection == 'user'){
				layoutProgressOn(dhxLayout);
				UserRolebusinessAuthorize.delAllRolesOfUserAndAddUserRoles(userId, myBusinessGrid.getSelectedId(),
	   				function(data){
	   					if(data == true){
	   						parent.notifyCreater('业务角色绑定成功');layoutProgressOff(dhxLayout);
	   					}else{
	   						parent.notifyWarn('业务角色绑定失败');layoutProgressOff(dhxLayout);
	   					}
	   				}
				);
			}else{
				parent.notifyWarn('请选择绑定的组织或用户');
			}
		}
	};
	
	function configGridSystem(){
		mySystemGrid.setHeader('');
		mySystemGrid.setNoHeader(true);
	    mySystemGrid.setColAlign("center");
	    mySystemGrid.setColTypes("ro");
	    mySystemGrid.enableMultiselect(true);
	    mySystemGrid.init();
	    setSkin(mySystemGrid);
	    mySystemGrid.loadXML('<%=basePath%>system-roleSystem/RoleSystemAction!roleSystemGridForBindAUnitUsers.action?userId=');
	}
	
	var dhxSystemGrid = {
		bind : function (){
			if(bindDirection == 'oragnation'){
				layoutProgressOn(dhxLayout);
				UserRolesystemAuthorize.delAllRoleUsersOfUnitAndAddUsersRoleOfUnit(myTreeOfUnitId, mySystemGrid.getSelectedId(),
	   				function(data){
	   					if(data == true){
	   						parent.notifyCreater('系统角色绑定成功');layoutProgressOff(dhxLayout);
	   					}else{
	   						parent.notifyWarn('系统角色绑定失败');layoutProgressOff(dhxLayout);
	   					}
	   				}
	   			);
			}else if(bindDirection == 'user'){
				layoutProgressOn(dhxLayout);
				UserRolesystemAuthorize.delAllRolesOfUserAndAddUserRoles(userId, mySystemGrid.getSelectedId(),
	   				function(data){
	   					if(data == true){
	   						parent.notifyCreater('系统角色绑定成功');layoutProgressOff(dhxLayout);
	   					}else{
	   						parent.notifyWarn('系统角色绑定失败');layoutProgressOff(dhxLayout);
	   					}
	   				}
	   			);
			}else{
				parent.notifyWarn('请选择绑定的组织或用户');
			}
		}
	};
	
	function filterByContentForSystem(){
		document.getElementsByTagName("input")[0].name = 'gridFilter';
		document.getElementsByTagName("input")[0].id = "wnameFilter_0";
		filterBy(mySystemGrid);// the method in grid.js
	}
	
	function inputOnclickForSystem(){
		(arguments[0]||window.event).cancelBubble=true;
	}
	
	function initInputEventForSystem(){
		var input = document.getElementsByTagName("input");
	 	input[0].onclick = inputOnclickForSystem; 
	 	input[0].onkeyup = filterByContentForSystem;
	}
	
	function filterByContentForBusiness(){
		document.getElementsByTagName("input")[1].name = 'gridFilter1';
		document.getElementsByTagName("input")[1].id = "wnameFilter1_0";
		filterBy(myBusinessGrid,'gridFilter1');// the method in grid.js
	}
	
	function inputOnclickForBusiness(){
		(arguments[0]||window.event).cancelBubble=true;
	}
	
	function initInputEventForBusiness(){
		var input = document.getElementsByTagName("input");
	 	input[1].onclick = inputOnclickForBusiness; 
	 	input[1].onkeyup = filterByContentForBusiness;
	}
	
	function operateTabbar(tabbar){
		tabbar.addTab("a1", "用户信息", "70px");
		tabbar.addTab("a2", "用户详细", "70px");
		tabbar.addTab("a3", "头像", "70px");
		tabbar.addTab("a4", "主题", "70px");
		tabbar.addTab("a5", "模板", "70px");
		tabbar.setContentHref("a1", "<%=basePath%>system-user/UserAction!userQueryForEdit.action?userMainId="+userId );
		tabbar.setContentHref("a2", "<%=basePath%>system-user/UserAction!userInfoQueryForEdit.action?userMainId="+userId );
		tabbar.setContentHref("a3", "<%=basePath%>system-user/UserAction!userImgQueryForEdit.action?userMainId="+userId );
		tabbar.setContentHref("a4", "<%=basePath%>system-user/UserAction!userThemeQuery.action?userMainId="+userId );
		tabbar.setContentHref("a5", "<%=basePath%>system-user/UserAction!userDisplayQuery.action?userMainId="+userId );
		tabbar.setTabActive("a1");
	}
	
	function changeRightPage(url){
		dhxLayout.cells('b').attachURL(url);
	}
	
	var detachUserId;
	function openUnits(userId){
		detachUserId = userId;
		unitWindow = openNewWindowURL('选择单位','<%=basePath%>page/system/chooseComponent/chooseUnit.jsp');
	}
	
	function getChooseUnitResult(ids,names,newaddIds,newaddNames,deletedIds){
		if(ids == '' || ids == null){
			parent.notifyWarn('没有选择单位');
			return;
		}
		layoutProgressOn(dhxLayout);
		userService.insertTUserUnits(detachUserId, ids, function(data){
			parent.notifyCreater('添加成功');
			closeUnits();
			window.location.href = '<%=basePath%>/page/system/user/main_user_unit.jsp';
		});
	}
	
	function closeUnits(){
		if(unitWindow){
			unitWindow.close();
		}
	}
	var unitGrid;
	var unitIdForAddExits;
	function openUsers(unitId,allExitsIds,mygrid){
		unitIdForAddExits = unitId;
		unitGrid = mygrid;//修改子页得grid
		userWindow = openNewWindowURL('选择用户','<%=basePath%>page/system/chooseComponent/chooseUser.jsp?userIds=' + allExitsIds);
	}
	
	function getChooseUsesrResult(ids,names,loginCodes,newaddIds,newaddNames,newaddLoginCodes,deletedIds){
		try {
			if((ids == null || ids == '')){
				parent.parent.notifyWarn('您没有选择用户');
			} else {
				layoutProgressOn(dhxLayout);
				userService.insertAndDeleteUsersToUnit(newaddIds,deletedIds,unitIdForAddExits,function(data){
					//tree update
					if(newaddIds != null && newaddIds != ''){
						var addIds = newaddIds.split(',');
						var addNames = newaddNames.split(',');
						for(var i=0;i<addIds.length;i++){
							MyTree.addNode(unitIdForAddExits, addIds[i] + '|' + unitIdForAddExits, addNames[i], 0, "man.gif", 0, 0, "");
							MyTree.setUserDataAttr(addIds[i], "type", "user");
						}
					}
					if(deletedIds != null && deletedIds != ''){
						var delIds = deletedIds.split(',');
						for(var i=0;i<delIds.length;i++){
							MyTree.delNode(delIds[i] + "|" + unitIdForAddExits);
						}
					}
					MyTree.refreshNode(unitIdForAddExits);
					//b cell reflash;
					src = '<%=basePath%>page/system/user/user_list.jsp?unitId='+ unitIdForAddExits;
					changeRightPage(src);
					parent.parent.notifyCreater('操作成功');
					layoutProgressOff(dhxLayout);
					closeUsers();
				});
			}
		} catch (ex) {
			myAlert(ex);
		}
	}
	
	function closeUsers(){
		if(userWindow){
			userWindow.close();
		}
	}
	
	function addUserPage(unitId){
		addUserWindow = openNewWindowURL('添加新用户','<%=basePath%>page/system/user/user_add.jsp?unitId=' + unitId);
	}
	
	function addUserPageClose(userMainId){
		if(userMainId != null && userMainId != ''){
			src = '<%=basePath%>page/system/user/user_list.jsp?unitId='+ myTreeOfUnitId+'&willSelectedUserMainId=' + userMainId;
			changeRightPage(src);
			reloadSystemAndBusinessGrid(userMainId);
		}
		if(addUserWindow){
			addUserWindow.close();
		}
	}
	
	</script>
</head>

<body>
<input type="hidden" id="sessionUserUnitIds" value="<%=unitIds %>" />
</body>

</html>
